package org.droidplanner.android.zz;

import android.content.Context;
import android.content.SharedPreferences;


import org.droidplanner.android.DroidPlannerApp;


/**
 * @author ZhaoZheng
 * @description: 本地保存数据工具类
 * @date :2024/3/14
 */
public class SpEasy {
    private static final String PREFERENCE_NAME = "save_data";

    public static <T> void saveData(String key, T value) {
        SharedPreferences sharedPreferences = DroidPlannerApp.app.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();

        if (value instanceof String) {
            editor.putString(key, (String) value);
        } else if (value instanceof Integer) {
            editor.putInt(key, (Integer) value);
        } else if (value instanceof Boolean) {
            editor.putBoolean(key, (Boolean) value);
        } else if (value instanceof Float) {
            editor.putFloat(key, (Float) value);
        } else if (value instanceof Long) {
            editor.putLong(key, (Long) value);
        }

        editor.apply();
    }

    public static <T> T getData(String key, T defaultValue) {
        SharedPreferences sharedPreferences = DroidPlannerApp.app.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);

        if (defaultValue instanceof String) {
            return (T) sharedPreferences.getString(key, (String) defaultValue);
        } else if (defaultValue instanceof Integer) {
            return (T) (Integer) sharedPreferences.getInt(key, (Integer) defaultValue);
        } else if (defaultValue instanceof Boolean) {
            return (T) (Boolean) sharedPreferences.getBoolean(key, (Boolean) defaultValue);
        } else if (defaultValue instanceof Float) {
            return (T) (Float) sharedPreferences.getFloat(key, (Float) defaultValue);
        } else if (defaultValue instanceof Long) {
            return (T) (Long) sharedPreferences.getLong(key, (Long) defaultValue);
        }

        return null;
    }

    public static void clearAllData(Context context) {
        SharedPreferences sharedPreferences = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.clear();
        editor.apply();
    }
}
